package main

import (
	"fmt"
	"sync"
	"time"
)

var ticket = 10

var wg sync.WaitGroup

func main() {
	wg.Add(10)
	go saleManager("张三")
	go saleManager("李四")
	go saleManager("王五")
	go saleManager("瘪三")
	go saleManager("老狗")
	//多个goroutine使用同一个变量导致数据不一致使得判断出现问题

	fmt.Println("main 等待ing")
	wg.Wait()
	fmt.Println("程序结束")
	//time.Sleep(time.Second * 3)
	//运用同步等待组让主程序在goroutine运行完后及时结束
}

func saleManager(name string) {

	for {

		if ticket > 0 {

			time.Sleep(time.Millisecond)

			fmt.Println(name, "抢了一张票")
			ticket--
			fmt.Println("剩余票为", ticket)
		} else {

			fmt.Println("票已经售完")
			break
		}
		wg.Done()
	}
}
